﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CSScriptLib;

namespace FieldTools.Util.Helper
{
    /// <summary>
    /// C#脚本帮助类
    /// </summary>
    public class CShapeScriptHepler
    {
        /// <summary>
        /// 执行C#脚本，入口方法原型为“public object Excute()”，必不可少
        /// </summary>
        /// <param name="scriptStr"></param>
        /// <param name="parm"></param>
        /// <returns></returns>
        public static string ExcuteScript(string scriptStr, object parm)
        {
            if(string.IsNullOrEmpty(scriptStr)) return "执行脚本不可空";
            try
            {
                //dynamic loadmethod = CSScript.Evaluator.LoadMethod(@"using System;
                //          public object Excute()
                //          {
                //              Console.WriteLine(""LoadMethod:"");
                //          }");
                //loadmethod.LoadMethod();
                dynamic loadmethod = CSScript.Evaluator.LoadMethod(scriptStr);
                return loadmethod.Excute(parm);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 执行c#脚本
        /// </summary>
        /// <param name="scriptStr"></param>
        /// <param name="parms"></param>
        /// <returns></returns>
        public static object ExcuteScript(string scriptStr, object[] parms)
        {
            return ExcuteScript(scriptStr, "Excute", parms);
        }

        /// <summary>
        /// 执行c#脚本
        /// </summary>
        /// <param name="scriptStr">脚本内容</param>
        /// <param name="entMethod">入口方法</param>
        /// <param name="parms">传入参数</param>
        /// <returns></returns>
        public static object ExcuteScript(string scriptStr, string entMethod, object[] parms)
        {
            if (string.IsNullOrEmpty(scriptStr)) return "执行脚本不可空";
            try
            {
                //Assembly compilemethod = CSScript.RoslynEvaluator.CompileMethod(
                //       @"using System;
                //          public static object entMethod(string greeting)
                //          {
                //              Console.WriteLine(""CompileMethod:"" + greeting);
                //          }");
                //var p = compilemethod.GetType("css_root+DynamicClass");
                //var me = p.GetMethod("entMethod");
                //me.Invoke(null, new object[] { "1" });

                Assembly compilemethod = CSScript.RoslynEvaluator.CompileMethod(scriptStr);
                var p = compilemethod.GetType("css_root+DynamicClass");
                if (p == null) return null;
                var me = p.GetMethod(entMethod);
                return me.Invoke(null, parms);
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
